function load() {
    init();
}

var data = [];

function init() {
    var num = 28;
    add(num);
    $("#loop").onclick = function () {
        loop();
    }
    $("#search").onclick = function () {
        search();
    }
}

function add(num) {
    for (var i = 0; i < num; i++) {
        data[i] = document.createElement("div");
        data[i].appendChild(document.createTextNode(i));
    }
    for (var j = data.length - 1; j > 0; j--) {
        var tmp = Math.floor((j - 1) / 3);
        var child = data[tmp].children;
        if (child.length != 0) {
            data[tmp].insertBefore(data[j], child[0]);
        } else {
            data[tmp].appendChild(data[j]);
        }

    }
    $("#tree").appendChild(data[0]);
}

function loop() {
    var i = 0;
    function run() {
        if (i <= data.length) {
            if (i - 1 >= 0 || i - 1 === data.length - 1) {
                data[i - 1].style.backgroundColor = "white";
                if (i - 1 === data.length - 1) {
                    clearInterval(int);
                    return;
                }
            }
            data[i].style.backgroundColor = "blue";
            i++;
        }
    }
    var int=setInterval(run, 1000);
}

function search() {
    var str = $("#text").value;
    var i = 0;
    function run() {
        if (i > data.length) {
            clearInterval(int);
            return;
        }
        if (i - 1 >= 0 || i - 1 === data.length - 1) {
            data[i - 1].style.backgroundColor = "white";
            if (i - 1 === data.length - 1) {
                clearInterval(int);
                return;
            }
        }
        data[i].style.backgroundColor = "blue";
        var childI = data[i].children;
        if (childI.length > 0) {
            if (data[i].innerText[0] === str) {
                data[i].style.backgroundColor = "yellow";
                clearInterval(int);
                return;
            }
        } else {
            if (data[i].innerText === str) {
                data[i].style.backgroundColor = "yellow";
                clearInterval(int);
                return;
            }
        }
        i++;
    }
    var int=setInterval(run, 1000);
}

function $(el) {
    return document.querySelector(el);
}